import {getToken} from "@/util/request.js";

const AVATAR_URL = "url('/api/system/avatar/preview')"
const DEFAULT_AVATAR_URL = "url('/logo.png')"

function makeAvatarUrl(hashcode) {
    if (!!hashcode) {
        return `url('/api/system/avatar/preview?file=${hashcode}&Authorization=${getToken()}')`
    } else {
        return DEFAULT_AVATAR_URL;
    }
}

export default {
    namespaced: true,
    state() {
        return {
            userInfo: null,
            menuList: [],
            menuLoaded: false,
            permissionList: [],
            //里面装的是页面视图的列表，与菜单不同，它里面有不是菜单的视图信息
            viewInfoList: [],
            avatarUrl: makeAvatarUrl(),
        }
    },
    getters: {
        userInfo: state => state.userInfo,
        permissionList: state => state.permissionList,
        menuList: state => state.menuList
    },
    mutations: { // mutations中放同步操作，即不需要请求后端的操作
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
            if (userInfo) {
                state.avatarUrl = makeAvatarUrl(userInfo.avatarFileHashCode)
            } else {
                state.avatarUrl = null
            }
        },
        setMenuList(state, menuList) {
            state.menuList = menuList
            state.menuLoaded = true
        },
        setPermissionList(state, permissionList) {
            //设置权限列表，把用户的菜单剥离出来
            state.permissionList = permissionList
        },
        setViewInfoList(state, viewInfoList) {
            state.viewInfoList = viewInfoList
        },
        setAvatar(state, fileHashCode) {
            state.avatarUrl = makeAvatarUrl(fileHashCode)
        }
    },
    actions: { //actions中放异步操作，即需要请求后端的操作
        login(context, userInfo) {
            context.commit("setUserInfo", userInfo)
            //处理菜单
            context.commit("setMenuList", userInfo.menuTree);
            context.commit("setPermissionList", userInfo.permissionList);
        },
        logout(context) {
            context.commit("setUserInfo", null)
        },
    }
}
